package conson.tech.manage.app.controller.mobile;


import cn.hutool.json.JSONUtil;
import conson.tech.core.constant.SecurityConstants;
import conson.tech.core.response.Response;
import conson.tech.manage.api.app.constant.AppCommon;
import conson.tech.manage.api.app.form.AppQueryForm;
import conson.tech.manage.app.entity.mobile.vo.*;
import conson.tech.manage.app.entity.pojo.AppConfig;
import conson.tech.manage.app.entity.pojo.AppVersion;
import conson.tech.manage.app.service.AppNewMobileService;
import conson.tech.manage.app.service.AppVersionService;
import conson.tech.manage.common.constant.BusinessMessage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * ClassName: AppNewMobileController
 * Description: app端新的内容控制
 * Author: HXL
 * Date: 2020/6/8 7:10 下午
 * Version: 1.0
 */
@Slf4j
@RequestMapping(SecurityConstants.MOBILEAPI)
@RestController
@RefreshScope
@Api(tags = "app端新的内容控制器")
public class AppNewMobileController extends BaseController {

    @Autowired
    private AppNewMobileService appNewMobileService;
    @Autowired
    private AppVersionService appVersionService;
    @Value("${card.holder.group.id}")
    private String cardHolderGroupId;
    @ApiOperation(value = "首页信息获取", notes = "获取首页的banner，icon，楼层等")
    @ApiImplicitParam(name = "appCommonMobileVo", value = "首页请求入参封装", required = true, dataType = "AppCommonMobileVo")
    @PostMapping("/newHome")
    public Response<IndexVo> appHome(@RequestBody AppCommonMobileVo appCommonMobileVo, HttpServletRequest request) {
        Long userId = super.getCurrentUserId(request);
        log.info("【首页信息】入参:【{}】,用户userID:【{}】",JSONUtil.toJsonStr(appCommonMobileVo),userId);
        AppQueryForm form = setAppQueryForm(appCommonMobileVo.getAppInfo(), AppCommon.PAGE_TYPE_ZERO);
        Integer versionValue = getAdVersionValue(form);//获取版本值
        if (versionValue == null){
            log.info("【首页信息】根据入参设置的参数:【{}】没有获取到版本值", JSONUtil.toJsonStr(form));
            return Response.success();
        }
       IndexVo indexVo =  appNewMobileService.assembleAppMobilePageData(userId,versionValue,form);
        return Response.success(indexVo);

    }
    @ApiOperation(value = "生活页信息获取", notes = "获取生活页面的banner，icon，楼层等")
    @ApiImplicitParam(name = "appCommonMobileVo", value = "生活请求入参封装", required = true, dataType = "AppCommonMobileVo")
    @PostMapping("/newLife")
    public Response<IndexVo> appLife(@RequestBody AppCommonMobileVo appCommonMobileVo, HttpServletRequest request) {
        Long userId = super.getCurrentUserId(request);
        log.info("【生活页信息】入参:【{}】,用户userID:【{}】",JSONUtil.toJsonStr(appCommonMobileVo),userId);
        AppQueryForm form = setAppQueryForm(appCommonMobileVo.getAppInfo(), AppCommon.PAGE_TYPE_ONE);
        Integer versionValue = getAdVersionValue(form);//获取版本值
        if (versionValue == null){
            log.info("【生活页信息】根据入参设置的参数:【{}】没有获取到版本值", JSONUtil.toJsonStr(form));
            return Response.success();
        }
        IndexVo indexVo =  appNewMobileService.assembleAppMobilePageData(userId,versionValue,form);
        return Response.success(indexVo);
    }



    @ApiOperation(value = "保存用户自定义首页", notes = "用户可自定义首页icon，注意，不可编辑图标必须存在")
    @ApiImplicitParam(name = "indexSaveVo", value = "保存自定义列表入参", required = true, dataType = "IndexSaveVo")
    @PostMapping("/icon/save")
    public Response saveCustomIndex(@RequestBody IndexSaveVo indexSaveVo, HttpServletRequest request) {

        Long userId = super.getCurrentUserId(request);

        if (userId == null) {
            return Response.fail(BusinessMessage.GET_USER_INFO_FROM_HEADER_FAILED);
        }

        boolean flag = false;
        try {
            flag = appNewMobileService.saveIndex(userId, indexSaveVo.getIconIdList());
        } catch (Exception e) {
            log.error("AppNewMobileController --> saveCustomIndex exception, userId {}", userId, e);
        }

        if (!flag) {
            return Response.fail(BusinessMessage.SAVE_USER_INDEX_FAILED);
        }

        return Response.success();
    }

    @ApiOperation(value = "积分页icon组返回", notes = "积分页接口")
    @ApiImplicitParam(name = "appCommonMobileVo", value = "通用请求", required = true, dataType = "AppCommonMobileVo")
    @PostMapping("/newCredit")
    public Response<CreditModuleVo> getCreditGroupInfo(@RequestBody AppCommonMobileVo appCommonMobileVo, HttpServletRequest request) {
        Long userId = super.getCurrentUserId(request);
        log.info("【信豆页信息】入参:【{}】,用户userID:【{}】",JSONUtil.toJsonStr(appCommonMobileVo),userId);
        AppQueryForm form = setAppQueryForm(appCommonMobileVo.getAppInfo(), AppCommon.APP_PLATE_TYPE_FOUR);
        Integer versionValue = getAdVersionValue(form);//获取版本值
        if (versionValue == null){
            log.info("【信豆页信息】根据入参设置的参数:【{}】没有获取到版本值", JSONUtil.toJsonStr(form));
            return Response.success();
        }
        AppConfig appConfig = new AppConfig();
        appConfig.setPlateType(AppCommon.APP_PLATE_TYPE_FOUR);
        CreditModuleVo  creditModuleVo=  appNewMobileService.appQueryLetterBean(appConfig , versionValue,form);
        return Response.success(creditModuleVo);
    }

    @ApiOperation(value = "全部icon获取接口", notes = "获取更多图标中的全部icon数据，并分组封装")
    @ApiImplicitParam(name = "appCommonMobileVo", value = "获取全部icon请求入参封装", required = true, dataType = "AppCommonMobileVo")
    @PostMapping("/newMore")
    public Response<List<ModuleVo>> getAllIcon(@RequestBody AppCommonMobileVo appCommonMobileVo, HttpServletRequest request) {
        Long userId = super.getCurrentUserId(request);
        log.info("【全部icon获取接口】入参:【{}】,用户userID:【{}】",JSONUtil.toJsonStr(appCommonMobileVo),userId);
        AppQueryForm form = setAppQueryForm(appCommonMobileVo.getAppInfo(), AppCommon.GROUP_TYPE_TWO);
        Integer versionValue = getAdVersionValue(form);//获取版本值
        if (versionValue == null){
            log.info("【全部icon获取接口】根据入参设置的参数:【{}】没有获取到版本值", JSONUtil.toJsonStr(form));
            return Response.success();
        }
        List<ModuleVo> moduleVOList =  appNewMobileService.queryAppGroupByType(form, versionValue);
        return Response.success(new CommonListVO(moduleVOList));
    }
    @ApiOperation(value = "展示分组信息", notes = "用于西海岸、国信集团等读取分组icon信息")
    @ApiImplicitParam(name = "commonQueryVo", value = "通用请求，输入groupId", required = true, dataType = "CommonQueryVo")
    @PostMapping("/newGroupInfo")
    public Response<ModuleVo> getGroupIconInfo(@RequestBody CommonQueryVo commonQueryVo, HttpServletRequest request) {
        Long userId = super.getCurrentUserId(request);
        log.info("【展示分组信息】入参:【{}】,用户userID:【{}】",JSONUtil.toJsonStr(commonQueryVo),userId);
        AppQueryForm form = setAppQueryForm(commonQueryVo.getAppInfo(), AppCommon.GROUP_TYPE_THREE);
       /* Integer versionValue = getAdVersionValue(form);//获取版本值
        if (versionValue == null){
            log.info("【展示分组信息】根据入参设置的参数:【{}】没有获取到版本值", JSONUtil.toJsonStr(form));
            return Response.success();
        }*/
        ModuleVo moduleVo =  appNewMobileService.queryGroupByGroupId(Long.valueOf(commonQueryVo.getId()),null,form);
        return Response.success(moduleVo);

    }
    @ApiOperation(value = "卡包展示", notes = "卡包接口，数据固定")
    @ApiImplicitParam(name = "appCommonMobileVo", value = "通用请求", required = true, dataType = "AppCommonMobileVo")
    @PostMapping("/newCardInfo")
    public Response getCardGroupInfo(@RequestBody AppCommonMobileVo appCommonMobileVo, HttpServletRequest request) {
        Long userId = super.getCurrentUserId(request);
        log.info("【卡包展示】入参:【{}】,用户userID:【{}】",JSONUtil.toJsonStr(appCommonMobileVo),userId);
        AppQueryForm form = setAppQueryForm(appCommonMobileVo.getAppInfo(), AppCommon.GROUP_TYPE_THREE);
       /* Integer versionValue = getAdVersionValue(form);//获取版本值
        if (versionValue == null){
            log.info("【卡包展示】根据入参设置的参数:【{}】没有获取到版本值", JSONUtil.toJsonStr(form));
            return Response.success();
        }*/
        ModuleVo moduleVo =  appNewMobileService.queryGroupByGroupId(Long.valueOf(cardHolderGroupId),null,form);
        return Response.success(moduleVo);

    }
    @ApiOperation(value = "获取版本信息")
    @ApiImplicitParam(name = "appCommonMobileVo", value = "通用请求", required = true, dataType = "AppCommonMobileVo")
    @PostMapping("/newAppVersion")
    public Response<ConfigVo> getVersionConfig(@RequestBody AppCommonMobileVo appCommonMobileVo, HttpServletRequest request) {
        Long userId = super.getCurrentUserId(request);
        log.info("【获取版本信息】入参:【{}】,用户userID:【{}】",JSONUtil.toJsonStr(appCommonMobileVo),userId);
        AppQueryForm form = setAppQueryForm(appCommonMobileVo.getAppInfo(), null);
        ConfigVo configVo =  appNewMobileService.getVersionConfig(form.getVersion(),form.getPlatformType());
        if (configVo == null){
            return Response.fail("获取版本信息失败");
        }
        return Response.success(configVo);

    }
    @ApiOperation(value = "Android获取版本信息")
    @ApiImplicitParam(name = "appCommonMobileVo", value = "通用请求", required = true, dataType = "AppCommonMobileVo")
    @PostMapping("/newAndroidAppVersion")
    public Response<ConfigVo> getAndroidVersionConfig(@RequestBody AppCommonMobileVo appCommonMobileVo, HttpServletRequest request) {
        Long userId = super.getCurrentUserId(request);
        log.info("【获取版本信息】入参:【{}】,用户userID:【{}】",JSONUtil.toJsonStr(appCommonMobileVo),userId);
        AppQueryForm form = setAppQueryForm(appCommonMobileVo.getAppInfo(), null);
        ConfigVo configVo =  appNewMobileService.getAndroidVersionConfig(form.getVersion(),form.getPlatformType());
        if (configVo == null){
            return Response.fail("获取版本信息失败");
        }
        return Response.success(configVo);

    }


    private AppQueryForm setAppQueryForm(AppInfoVo appInfo, Integer type) {
        AppQueryForm form = new AppQueryForm();
        //平台类型1 iOS 2 android 不能为空
        if ("0".equals(appInfo.getSourceSystem())) {
            form.setPlatformType(1);
        }else {
            form.setPlatformType(2);
        }
        form.setType(type);
       if (!appInfo.getAppVersion().toLowerCase().contains("v")){
        form.setVersion("v"+appInfo.getAppVersion());
       }else {
           form.setVersion(appInfo.getAppVersion().toLowerCase());
       }
        return form;
    }
    private Integer getAdVersionValue(AppQueryForm form) {
        List<AppVersion> versionList = appVersionService.queryAppVersionByVersionNum(form.getVersion(),form.getPlatformType());
        if (CollectionUtils.isEmpty(versionList)){
            return  null;
        }
        if (versionList.get(0).getVersionState() == AppCommon.VERSION_STATE_ONE){//是最新版本
            return AppCommon.VERSION_VALUE;
        }else {
            return versionList.get(0).getVersionValue();
        }
    }
}
